<template>
   <el-card class="box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button type="primary" icon="Plus" @click="addTrademark" v-has="`btn.Trademark.add`">添加品牌</el-button>
      <!-- 表格组件：用于展示已有的平台数据 -->
      <el-table border style="margin:10px 0px;" :data="trademarkArr">
         <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
         <!-- 默认展示数据为div -->
         <el-table-column label="品牌名称" prop="tmName"></el-table-column>
         <el-table-column label="品牌LOGO">
            <template #="{ row, $index }">
               <img :src="row.logoUrl" style="width: 10vw; height: 10vw;">
            </template>
         </el-table-column>
         <el-table-column label="品牌操作">
            <template #="{ row, $index }">
               <el-button type="primary" icon="Edit" @click="updateTrademark(row)"></el-button>
               <el-popconfirm :title="`你确定要删除${row.tmName}?`" width="250px" icon="Delete"
                  @confirm="removeTradeMark(row.id)">
                  <template #reference>
                     <el-button type="primary" icon="Delete"></el-button>
                  </template>
               </el-popconfirm>
            </template>
         </el-table-column>
      </el-table>
      <!-- 
         分页器
            v-model:current-page：设置分页器当前页面
            v-model:page-size：设置每页展示数据条数
            page-sizes:用于设置下拉菜单数据
            background:设置分页器按钮的背景颜色
            layout：设置分页器子组件的布局
       -->
      <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" :background="true"
         layout="prev, pager, next, jumper, ->, sizes, total" :total="total" @current-change="getHasTrademark"
         @size-change="sizeChange" />
   </el-card>
   <!-- 对话框组件 -->
   <!-- 
      dialogFormVisible用于控制对话框的显示与隐藏
      title:设置对话框左上角标题
    -->
   <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
      <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
         <el-form-item label="品牌名称" label-width="100px" prop="tmName">
            <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
         </el-form-item>
         <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
            <!-- upload组件属性：action图片上传路径 -->
            <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
               :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
               <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
               <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
               </el-icon>
            </el-upload>

         </el-form-item>
      </el-form>
      <!-- 具名插槽footer -->
      <template #footer>
         <el-button @click="cancel">取消</el-button>
         <el-button type="primary" @click="confirm">确定</el-button>
      </template>
   </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { reqHasTrademark, reqAddOrUpdateTradeMark, reqDeleteTradeMark } from '@/api/product/trademark'
import type { Records, TradeMarkResponseData, TradeMark } from '@/api/product/trademark/type'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

// 当前页码
let pageNo = ref<number>(1)
// 每一页展示多少条数据
let limit = ref<number>(3)
// 存储已有品牌数据总数
let total = ref<number>(0)
// 存储已有品牌的数据
let trademarkArr = ref<Records>([])
// 控制对话框的显示与隐藏
let dialogFormVisible = ref<boolean>(false)
// 定义一个收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
   tmName: '',
   logoUrl: ''

})
// 获取el-form组件实例
let formRef = ref()
// 获取已有品牌数据封装为一个函数
const getHasTrademark = async (pager = 1) => {
   pageNo.value = pager
   let result: TradeMarkResponseData = await reqHasTrademark(pager, limit.value)
   if (result.code == 200) {
      total.value = result.data.total
      trademarkArr.value = result.data.records
   }
}
onMounted(() => {
   getHasTrademark()
})
// 分页器当前页码变化时触发回调
// const changeNo = () => {
//    // 再次发起请求获取已有品牌数据
//    getHasTrademark()
// }

// 当下拉菜单发生变化时会触发此方法
// 这个自定义事件，分页器组件会将下拉菜单选中的数据返回
const sizeChange = () => {
   // 每页显示数据量变化时，页码归1
   pageNo.value = 1
   getHasTrademark()
}
// 添加品牌按钮的回调
const addTrademark = () => {
   dialogFormVisible.value = true
   // 收集数据清空
   trademarkParams.tmName = ''
   trademarkParams.logoUrl = ''
   trademarkParams.id = 0
   // 校验结果清空
   // 第一种方法：ts的问号语法
   // formRef.value?.clearValidate('tmName')
   // formRef.value?.clearValidate('logoUrl')
   // 第二种方法：nextTick()等dom结点渲染完毕后执行
   nextTick(() => {
      formRef.value.clearValidate('tmName')
      formRef.value.clearValidate('logoUrl')
   })
}
// 修改品牌按钮的回调
const updateTrademark = (row: TradeMark) => {
   // 清空校验规则的错误提示信息
   nextTick(() => {
      formRef.value.clearValidate('tmName')
      formRef.value.clearValidate('logoUrl')
   })
   dialogFormVisible.value = true
   // ES6合并对象
   Object.assign(trademarkParams, row)
}
// 起泡确认框确定按钮的回调
const removeTradeMark = async (id: number) => {
   // 发起删除品牌的请求
   let result = await reqDeleteTradeMark(id)
   if (result.code == 200) {
      ElMessage.success('删除品牌成功！')
      getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
   } else {
      ElMessage.error('删除品牌失败！')
   }
}
// 对话框底部取消按钮的回调
const cancel = () => {
   dialogFormVisible.value = false
}
// 对话框底部确定按钮的回调
const confirm = async () => {
   // 发请求之前，对表单进行校验
   await formRef.value.validate()
   let result: any = await reqAddOrUpdateTradeMark(trademarkParams)
   console.log(result)
   if (result.code == 200) {
      // 添加|修改成功
      // 关闭对话框
      dialogFormVisible.value = false
      ElMessage.success(trademarkParams.id ? '修改品牌成功！' : '添加品牌成功！')
      // 再次获取最新的全部品牌数据
      getHasTrademark(trademarkParams.id ? pageNo.value : 1)
   } else {
      // 添加失败
      ElMessage.error(trademarkParams.id ? `修改品牌失败!${result.data}` : '添加品牌失败！')
   }
}
// 上传图片之前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
   // 约束图片的类型和大小(png|jpg|gif)(4M)
   if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
      ElMessage.error('上传文件格式务必为JPG|PNG|GIF!')
      return false
   } else if (rawFile.size / 1024 / 1024 > 4) {
      ElMessage.error('上传的文件大小不能大于4M!')
      return false
   }
   return true
}
// 图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
   // response：即为当前这次上传图片post请求服务器返回的数据
   // 收集上传的图片的url地址
   trademarkParams.logoUrl = response.data
   // 图片上传成功，清除掉对应图片的校验结果
   formRef.value.clearValidate('logoUrl')
}
// 品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
   // 自定义校验规则
   if (value.trim().length >= 2) {
      // 校验成功
      callBack()
   } else {
      // 校验失败
      callBack(new Error('品牌名称长度应大于等于两位！'))
   }
}
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
   if (value) {
      callBack()
   } else {
      callBack(new Error('LOGO图片必须上传！'))
   }
}
// 表单校验规则对象
const rules = {
   tmName: [
      { required: true, trigger: 'blur', validator: validatorTmName }
   ],
   logoUrl: [
      { required: true, validator: validatorLogoUrl }
   ],
}


</script>

<style scoped>
.avatar-uploader .avatar {
   width: 178px;
   height: 178px;
   display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
   border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
   font-size: 28px;
   color: #8c939d;
   width: 178px;
   height: 178px;
   text-align: center;
}
</style>